#pragma once

#include <windows.h>

namespace DwUtility
{
	class DwCSLock
	{
	public:
		DwCSLock()
		{
			InitializeCriticalSection(&m_criticalSection);
		}

		~DwCSLock()
		{
			DeleteCriticalSection(&m_criticalSection);
		}

		void lock()
		{
			EnterCriticalSection(&m_criticalSection);
		}

		void unlock()
		{
			LeaveCriticalSection(&m_criticalSection);
		}

		bool tryLock()
		{
			return TryEnterCriticalSection(&m_criticalSection) ? true : false;
		}

	private:
		CRITICAL_SECTION m_criticalSection;
	};

	class DwAutoCSLocker
	{
	public:
		explicit DwAutoCSLocker(DwCSLock *m)
			: m_lock(m)
		{
			m_lock->lock();
		}

		~DwAutoCSLocker()
		{
			m_lock->unlock();
			m_lock = NULL;
		}

	private:
		DwCSLock *m_lock;
	};
}

#define DW_AUTO_LOCKER(x) DwUtility::DwAutoCSLocker ___auto_locker_blabla___(x);